using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.Utils;
using DevExpress.XtraEditors.Controls;

namespace WinForm_Mes.CheckManagement
{
    public partial class AddUserForm : DevExpress.XtraEditors.XtraForm
    {
        #region 私有字段
        private readonly string _baseUrl = "http://localhost:5078/api/User/";
        private readonly HttpClient _httpClient;
        private FormMode _mode = FormMode.Add;
        private UserDto _userData;
        #endregion

        #region 枚举
        public enum FormMode
        {
            Add,
            Edit,
            View
        }
        #endregion

        #region 构造函数
        public AddUserForm(FormMode mode = FormMode.Add, UserDto userData = null)
        {
            _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
            _mode = mode;
            _userData = userData ?? new UserDto();
            
            InitializeComponent();
            InitializeControls();
            ApplyStyles();
            BindEvents();
            LoadData();
        }
        #endregion

        #region 初始化和事件绑定
        private void InitializeControls()
        {
            // 设置窗体标题
            switch (_mode)
            {
                case FormMode.Add:
                    Text = "添加客户";
                    break;
                case FormMode.Edit:
                    Text = "编辑客户";
                    break;
                case FormMode.View:
                    Text = "客户详情";
                    break;
            }

            // 设置客户类型下拉框
            cmbUserType.Properties.Items.AddRange(new string[] { "个人用户", "企业用户", "合作伙伴", "其他" });
            
            // 如果是查看模式，禁用所有输入控件
            if (_mode == FormMode.View)
            {
                SetControlsReadOnly(true);
                btnSave.Visible = false;
                btnCancel.Text = "关闭";
            }
        }

        private void ApplyStyles()
        {
            // 设置窗体样式
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.StartPosition = FormStartPosition.CenterParent;
            
            // 美化标题
            lblTitle.Font = new Font("微软雅黑", 14F, FontStyle.Bold);
            lblTitle.ForeColor = Color.FromArgb(78, 116, 171);

            // 美化分隔线
            separatorControl1.LineColor = Color.FromArgb(78, 116, 171);
            separatorControl1.LineThickness = 2;

            // 美化面板
            panelControl1.Appearance.BackColor = Color.FromArgb(240, 244, 250);
            panelControl2.Appearance.BackColor = Color.White;

            // 美化标签和编辑框
            foreach (Control control in panelControl2.Controls)
            {
                if (control is LabelControl lbl)
                {
                    lbl.Appearance.Font = new Font("微软雅黑", 9F);
                    lbl.Appearance.ForeColor = Color.FromArgb(60, 60, 60);
                }
                else if (control is TextEdit txt)
                {
                    txt.Properties.Appearance.Font = new Font("微软雅黑", 9F);
                    txt.Properties.BorderStyle = BorderStyles.Simple;
                    txt.Height = 30;
                }
                else if (control is ComboBoxEdit cmb)
                {
                    cmb.Properties.Appearance.Font = new Font("微软雅黑", 9F);
                    cmb.Properties.BorderStyle = BorderStyles.Simple;
                    cmb.Height = 30;
                }
            }

            // 美化按钮
            btnSave.Appearance.BackColor = Color.FromArgb(78, 116, 171);
            btnSave.Appearance.ForeColor = Color.White;
            btnSave.Appearance.Font = new Font("微软雅黑", 9F);
            btnSave.Appearance.Options.UseBackColor = true;
            btnSave.Appearance.Options.UseForeColor = true;
            btnSave.Appearance.Options.UseFont = true;

            btnCancel.Appearance.BackColor = Color.FromArgb(210, 210, 210);
            btnCancel.Appearance.ForeColor = Color.Black;
            btnCancel.Appearance.Font = new Font("微软雅黑", 9F);
            btnCancel.Appearance.Options.UseBackColor = true;
            btnCancel.Appearance.Options.UseForeColor = true;
            btnCancel.Appearance.Options.UseFont = true;
        }

        private void BindEvents()
        {
            this.btnSave.Click += BtnSave_Click;
            this.btnCancel.Click += BtnCancel_Click;
            this.Load += AddUserForm_Load;
        }

        private void LoadData()
        {
            if (_mode == FormMode.Edit || _mode == FormMode.View)
            {
                // 填充现有用户数据
                txtUserCode.Text = _userData.userCode;
                txtUserName.Text = _userData.userName;
                txtPassword.Text = _userData.password;
                txtUserShortName.Text = _userData.userShortName;
                txtPhone.Text = _userData.phone;
                txtEmail.Text = _userData.email;
                cmbUserType.Text = _userData.userType;
                
                // 编辑模式下用户编码不允许修改
                if (_mode == FormMode.Edit)
                {
                    txtUserCode.ReadOnly = true;
                    txtUserCode.BackColor = Color.LightGray;
                }
            }
        }

        private void SetControlsReadOnly(bool readOnly)
        {
            txtUserCode.ReadOnly = readOnly;
            txtUserName.ReadOnly = readOnly;
            txtPassword.ReadOnly = readOnly;
            txtUserShortName.ReadOnly = readOnly;
            txtPhone.ReadOnly = readOnly;
            txtEmail.ReadOnly = readOnly;
            cmbUserType.ReadOnly = readOnly;

            if (readOnly)
            {
                txtUserCode.BackColor = Color.LightGray;
                txtUserName.BackColor = Color.LightGray;
                txtPassword.BackColor = Color.LightGray;
                txtUserShortName.BackColor = Color.LightGray;
                txtPhone.BackColor = Color.LightGray;
                txtEmail.BackColor = Color.LightGray;
                cmbUserType.BackColor = Color.LightGray;
            }
        }

        private void AddUserForm_Load(object sender, EventArgs e)
        {
            // 根据模式调整窗体外观
            if (_mode == FormMode.View)
            {
                // 如果是查看模式，隐藏密码
                txtPassword.Properties.PasswordChar = '*';
            }
        }
        #endregion

        #region 事件处理
        private async void BtnSave_Click(object sender, EventArgs e)
        {
            if (!ValidateInput())
            {
                return;
            }

            try
            {
                Cursor = Cursors.WaitCursor;
                btnSave.Enabled = false;

                // 准备用户数据
                var userData = new UserDto
                {
                    userCode = txtUserCode.Text.Trim(),
                    userName = txtUserName.Text.Trim(),
                    password = txtPassword.Text.Trim(),
                    userShortName = txtUserShortName.Text.Trim(),
                    phone = txtPhone.Text.Trim(),
                    email = txtEmail.Text.Trim(),
                    userType = cmbUserType.Text.Trim()
                };

                bool success = false;

                if (_mode == FormMode.Add)
                {
                    // 添加用户
                    success = await AddUserAsync(userData);
                }
                else if (_mode == FormMode.Edit)
                {
                    // 更新用户
                    success = await UpdateUserAsync(userData);
                }

                if (success)
                {
                    MessageBox.Show(_mode == FormMode.Add ? "添加成功！" : "更新成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DialogResult = DialogResult.OK;
                    Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"操作失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor = Cursors.Default;
                btnSave.Enabled = true;
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
        #endregion

        #region 业务方法
        private bool ValidateInput()
        {
            // 验证必填字段
            if (string.IsNullOrWhiteSpace(txtUserCode.Text))
            {
                MessageBox.Show("请输入客户编码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtUserCode.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(txtUserName.Text))
            {
                MessageBox.Show("请输入客户名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtUserName.Focus();
                return false;
            }

            if (_mode == FormMode.Add && string.IsNullOrWhiteSpace(txtPassword.Text))
            {
                MessageBox.Show("请输入密码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPassword.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(cmbUserType.Text))
            {
                MessageBox.Show("请选择客户类型", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                cmbUserType.Focus();
                return false;
            }

            // 验证电话格式
            if (!string.IsNullOrWhiteSpace(txtPhone.Text) && !System.Text.RegularExpressions.Regex.IsMatch(txtPhone.Text, @"^\d{11}$"))
            {
                MessageBox.Show("请输入正确的手机号码格式", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtPhone.Focus();
                return false;
            }

            // 验证邮箱格式
            if (!string.IsNullOrWhiteSpace(txtEmail.Text) && !System.Text.RegularExpressions.Regex.IsMatch(txtEmail.Text, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
            {
                MessageBox.Show("请输入正确的邮箱格式", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtEmail.Focus();
                return false;
            }

            return true;
        }

        private async Task<bool> AddUserAsync(UserDto userData)
        {
            try
            {
                var url = $"{_baseUrl}AddUser";
                var response = await _httpClient.PostAsJsonAsync(url, userData);

                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadFromJsonAsync<ApiResult>();
                    return result.Code == 200;
                }
                else
                {
                    MessageBox.Show($"添加失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"添加失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        private async Task<bool> UpdateUserAsync(UserDto userData)
        {
            try
            {
                var url = $"{_baseUrl}UpdateUser";
                var response = await _httpClient.PostAsJsonAsync(url, userData);

                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadFromJsonAsync<ApiResult>();
                    return result.Code == 200;
                }
                else
                {
                    MessageBox.Show($"更新失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"更新失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        #endregion

        #region 数据模型
        public class UserDto
        {
            public string userCode { get; set; } = string.Empty;
            public string userName { get; set; } = string.Empty;
            public string password { get; set; } = string.Empty;
            public string userShortName { get; set; } = string.Empty;
            public string phone { get; set; } = string.Empty;
            public string userType { get; set; } = string.Empty;
            public string email { get; set; } = string.Empty;
        }

        public class ApiResult
        {
            public int Code { get; set; }
            public string Message { get; set; }
            public object Data { get; set; }
        }
        #endregion

        private void AddUserForm_Load_1(object sender, EventArgs e)
        {

        }
    }
} 